<template>
    <el-dialog
        v-model="dialogVisible"
        @close="closeDialog"
        :close-on-click-modal="false"
        :title="`${memberDetail.id ? '编辑' : '新增'}会员`"
        top="90px"
        width="340px"
    >
        <el-form
            class="mr8 mt10"
            v-loading="dialogLoading"
            element-loading-background="rgba(0,0,0,0)"
            label-width="80px"
            ref="ruleFormRef"
            :rules="rules"
            :model="ruleForm"
        >
            <div :style="{ opacity: dialogLoading ? 0 : 1 }">
                <div v-if="memberDetail.id">
                    <el-form-item label="会员昵称" mb5>{{ memberDetail.nickname || `用户${memberDetail.mobile}` }}</el-form-item>
                    <el-form-item label="会员手机号" mb5>{{ memberDetail.mobile }}</el-form-item>
                    <el-form-item label="会员卡号" mb10>{{ memberDetail.sn }}</el-form-item>
                </div>
                <el-form-item v-else label="手机号" prop="mobile">
                    <el-input
                        id="mobile"
                        v-model="ruleForm.mobile"
                        show-word-limit
                        :maxlength="11"
                        placeholder="请输入手机号"
                        clearable
                    />
                </el-form-item>
                <el-form-item label="真实姓名" prop="real_name" :required="false">
                    <el-input
                        v-model="ruleForm.real_name"
                        show-word-limit
                        :maxlength="10"
                        placeholder="请输入真实姓名"
                        clearable
                    />
                </el-form-item>
                <el-form-item label="会员等级">
                    <el-select v-model="ruleForm.level_id" placeholder="请选择会员等级" clearable style="width: 100%;">
                        <el-option v-for="row in levelFilters" :key="row.id" :value="row.id" :label="row.name"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="性别">
                    <el-radio-group v-model="ruleForm.gender">
                        <el-radio v-for="row in genderRadios" :key="row.value" :value="row.value">{{ row.label }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="生日">
                    <el-date-picker
                        v-model="ruleForm.birthday"
                        :editable="false"
                        type="date"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择生日"
                        style="width: 100%;"
                    />
                </el-form-item>
                <el-form-item label="地区">
                    <div class="f-c" style="width: 100%;">
                        <el-select v-model="ruleForm.province" placeholder="请选择" @change="changeProvince">
                            <el-option v-for="row in provinceList" :key="row.id" :value="row.name" :label="row.name"/>
                        </el-select>
                        <el-select v-model="ruleForm.city" :loading="cityLoading" :disabled="!ruleForm.province" placeholder="请选择" class="ml5">
                            <el-option v-for="row in cityList" :key="row.id" :value="row.name" :label="row.name"/>
                        </el-select>
                    </div>
                </el-form-item>
                <div v-if="memberDetail.id">
                    <el-form-item label="积分" class="mb5">{{ memberDetail.point }}</el-form-item>
                    <el-form-item label="消费金额" class="mb5">{{ memberDetail.cost }}</el-form-item>
                    <el-form-item label="会员等级" class="mb0">{{ memberDetail.level_name }}</el-form-item>
                    <el-form-item v-if="!isPaidMember" label="会员标签" class="mb0 mt5" style="white-space: pre">{{ memberDetail.labels }}</el-form-item>
                </div>
            </div>
        </el-form>

        <template #footer>
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            <el-button
                class="mr8"
                type="primary"
                :loading="btnLoading"
                :disabled="btnLoading"
                @click="submitForm(ruleFormRef)"
            >
                确认
            </el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
    import { ref, reactive, watch, PropType, computed } from "vue";
    import { ElMessage } from "element-plus";
    import { FGender } from "@/filters";
    import { TypeFilters } from "@/interface/filters";
    import { _mallStore } from '@/store/config'
    import { storeToRefs } from "pinia";
    import { getRestfulLocations, getRestfulMallMemberDetail, postV3StoreMember, postV3UpdateMember } from "@/assets/api";
    import { getRestfulMallLevelsFilter } from "@/assets/api/handler";

    const { isPaidMember } = storeToRefs(_mallStore);
    const genderRadios = ref<TypeFilters.filter[]>(FGender);

    const props = defineProps({
        modelValue: {
            type: Boolean,
            default: false,
        },
        detail: {
            type: Object as PropType<ObjValueAny>,
            default: () => {
                return {}
            }
        },
    })

    const emit = defineEmits(['update:modelValue', 'update', 'add']);
    let dialogVisible = ref<boolean>(false);// 显示弹窗
    // 关闭弹窗
    const closeDialog = () => {
        cancelDialog();
        emit('update:modelValue', dialogVisible.value);
    }
    // 关闭弹窗
    const cancelDialog = () => {
        dialogVisible.value = false;
    }

    let ruleForm = ref<ObjValueAny>({});
    const resetRuleForm = () => {
        ruleForm.value = {
            mall_id: _mallStore.mallId,
            mobile: '',
            real_name: '',
            level_id: '',
            gender: FGender[0].value,
            birthday: '',
            province: '',
            city: '',
            publish_level_gifts: 0,// 会员等级发生变化 是否赠送等级礼 0:不赠送 1:赠送
        }
    }

    // 表单验证 字段
    const ruleFormRef = ref();
    let subStatus: boolean = false;
    const validatorMobile = (rule: object, value: string, callback: Function) => {
        if (subStatus) {
            if (!value || value.length < 11) {
                return callback(new Error('请输入11位手机号码'))
            }
        }
        callback()
    }
    const validatorRealName = (rule: object, value: string, callback: Function) => {
        if (subStatus && value.length === 1) {
            return callback(new Error('请输入正确的真实姓名'))
        }
        callback()
    }
    const rules = reactive<ObjValueAny>({
        mobile: [{ required: true, validator: validatorMobile, trigger: 'change' }],
        real_name: [{ required: true, validator: validatorRealName, trigger: 'change' }],
    });

    // 表单验证
    const submitForm = async (formEl: any) => {
        subStatus = true;
        if (!formEl) return;
        await formEl.validate((valid: boolean, fields: ObjValueAny) => {
            if (valid) {
                console.log('submit!');
                onSave();
            } else {
                console.log('error submit!', fields)
            }
        });
    }
    let subLoading = ref<boolean>(false);
    const onSave = () => {
        subLoading.value = true;
        if (memberDetail.value.id) {
            // 编辑会员
            postV3UpdateMember({
                mall_id: _mallStore.mallId,
                member_id: memberDetail.value.id,
                nickname: memberDetail.value.nickname,
                avatar: memberDetail.value.avatar || '',
                ...ruleForm.value,
            }).then((resp: { code: number, msg: string }) => {
                if (resp.code === 200) {
                    emit('update');
                    resetForm(ruleFormRef.value);
                } else {
                    ElMessage.error(resp.msg);
                    subLoading.value = false;
                }
            }).catch(() => {
                subLoading.value = false;
            })
        } else {
            // 新增会员
            postV3StoreMember({
                origin_type: 9,
                ...ruleForm.value,
            }).then((resp: { code: number, msg: string }) => {
                if (resp.code === 200) {
                    emit('add');
                    resetForm(ruleFormRef.value);
                } else {
                    ElMessage.error(resp.msg);
                    subLoading.value = false;
                }
            }).catch(() => {
                subLoading.value = false;
            })
        }
    }
    const resetForm = (formEl: any) => {
        if (!formEl) return
        cancelDialog();
        formEl.resetFields()
    }

    // 获取会员等级列表
    let levelFilters = ref<ObjValueAny[]>([]);
    const getLevelList = async () => {
        levelFilters.value = await getRestfulMallLevelsFilter();
    }

    // 获取地区
    interface TypeArea {
        id: number
        name: string
    }

    let provinceList = ref<TypeArea[]>([]);
    let cityList = ref<TypeArea[]>([]);
    let cityLoading = ref<boolean>(false);

    const changeProvince = async (name: string) => {
        cityList.value = [];
        ruleForm.value.city = '';
        if (name) {
            cityLoading.value = true;
            await getCityList(name);
            cityLoading.value = false;
            if (cityList.value && cityList.value.length) {
                ruleForm.value.city = cityList.value[0].name;
            }
        }
    }

    const getLocations = (params: ObjValueAny = {}): Promise<void> => {
        return new Promise(resolve => {
            getRestfulLocations({
                page: 1,
                per_page: 10000,
                mall_id: _mallStore.mallId,
                ...params
            }).then((resp: ObjValueAny) => {
                if (resp.code === 200) {
                    if (params.type === 1) {
                        provinceList.value = resp.data;
                    }
                    if (params.type === 2) {
                        cityList.value = resp.data;
                    }
                } else {
                    ElMessage.error(resp.msg);
                }
                resolve();
            });
        })
    }
    const getProvinceList = async () => {
        await getLocations({ type: 1 });
    }
    const getCityList = async (name: string) => {
        const { id } = provinceList.value.filter((row: TypeArea) => row.name === name)[0];
        await getLocations({ type: 2, location_id: id });
    }

    let dialogLoading = ref<boolean>(false);
    const btnLoading = computed(() => {
        return subLoading.value || dialogLoading.value;
    })

    let memberDetail = ref<ObjValueAny>({});
    watch(() => props.modelValue, (bool: boolean) => {
        dialogVisible.value = bool;
        subLoading.value = false;
        subStatus = false;
        if (bool) {
            resetRuleForm();
            getLevelList();
            if (props.detail.id) {
                dialogLoading.value = true;
                memberDetail.value = props.detail as ObjValueAny;
                getRestfulMallMemberDetail(props.detail.id).then(async (resp: ObjValueAny) => {
                    if (resp.code === 200) {
                        const { data } = resp;
                        await getProvinceList();
                        if (data.province) {
                            getCityList(data.province).then();
                        }
                        memberDetail.value = data;
                        let _label: string = '';
                        const labelGroups: ObjValueAny[] = data.label_groups || [];
                        if (labelGroups.length) {
                            _label = labelGroups[0].name;
                            if (labelGroups[0].labels[0]) {
                                _label = `${_label}-${labelGroups[0].labels[0].name}`;
                            }
                            if (labelGroups.length > 1) {
                                _label = `${_label} 等${labelGroups.length}个标签`;
                            }
                        }
                        memberDetail.value.labels = _label;
                        ruleForm.value.mobile = data.mobile;
                        ruleForm.value.real_name = data.real_name;
                        ruleForm.value.level_id = +data.level_id;
                        ruleForm.value.gender = +data.gender;
                        ruleForm.value.birthday = data.birthday;
                        ruleForm.value.province = data.province;
                        ruleForm.value.city = data.city;
                        dialogLoading.value = false;
                    } else {
                        ElMessage.error(resp.msg);
                    }
                })
            } else {
                getProvinceList();
                dialogLoading.value = false;
                memberDetail.value = {};
            }
        }
    })
</script>